package com.starxg.m3u8.controller;

import com.starxg.m3u8.gui.DialogUtils;
import com.starxg.m3u8.parser.M3U8Item;
import com.starxg.m3u8.parser.M3U8Parser;
import javafx.collections.ListChangeListener;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.input.Dragboard;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.stage.Window;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import java.util.List;
import java.util.ResourceBundle;
import java.util.function.Consumer;

@Slf4j
@Getter
public class ControlController extends BaseController implements InitializationControl<MainController>, InitializationWindow {

    /**
     * 解析事件
     */
    @Setter
    private Consumer<URL> analysisAction;

    /**
     * 下载事件
     */
    @Setter
    private Consumer<File> downloadAction;

    /**
     * 下载事件
     */
    @Setter
    private Runnable pauseAction;

    @FXML
    private VBox root;
    private MainController controller;
    @FXML
    private TextField txtSaveFilename;
    @FXML
    private MenuItem miAbout;
    @FXML
    private Label lblKeyMethod;
    @FXML
    private TextField txtKey;
    @FXML
    private Button btnAnalysis;
    @FXML
    private Button btnConfig;
    @FXML
    private TextField txtSavePath;
    @FXML
    private Button btnFileSavePath;
    @FXML
    private Button btnDownload;
    @FXML
    private Button btnPause;
    @FXML
    private TextField txtUrl;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
    }


    @Override
    public void init(MainController controller) {
        this.controller = controller;
        initView();
        initData();
        initEvent();
    }

    @Override
    public void initView() {
    }

    @Override
    public void initData() {

    }

    @Override
    public void initEvent() {
        btnAnalysis.setOnAction(event -> {

            // 判断是否有数据
            if (!controller.getTable().getItems().isEmpty()) {
                if (!confirm("当前列表有数据，继续操作将会清除列表。你确定要继续吗？")) {
                    return;
                }
            }

            String text = txtUrl.getText();

            if (StringUtils.isBlank(text)) {
                txtUrl.requestFocus();
                alert("请输入M3U8地址");
                return;
            }


            try {
                if (analysisAction != null) {
                    analysisAction.accept(new URL(text));
                }
            } catch (MalformedURLException ex) {
                log.error(ex.getMessage(), ex);
                alert("M3U8地址无法识别");
            }

        });

        btnFileSavePath.setOnAction(e -> {
            File file = DialogUtils.showDialog(null, null, getStage());
            if (file != null) {
                txtSavePath.setText(file.getAbsolutePath());
            }
        });

        btnDownload.setOnAction(e -> {

            if (StringUtils.isBlank(txtSavePath.getText())) {
                btnFileSavePath.fireEvent(new ActionEvent());
                return;
            } else if (!Files.exists(Path.of(txtSavePath.getText()))) {
                alert("没有找到路径：" + txtSavePath.getText());
                return;
            }

            if (StringUtils.isBlank(txtSaveFilename.getText())) {
                alert("请输入保存的文件名");
                return;
            }

            File file = new File(txtSavePath.getText(), txtSaveFilename.getText());

            if (file.exists()) {
                if (!confirm("文件已经存在，是否覆盖并继续?")) {
                    return;
                }

                try {
                    FileUtils.forceDelete(file);
                } catch (IOException ex) {
                    log.error(ex.getMessage(), ex);
                    alert("删除文件失败。原因：" + ex.getMessage(), Alert.AlertType.ERROR);
                    return;
                }

            }

            if (downloadAction != null) {
                downloadAction.accept(file);
            }

        });

        btnConfig.setOnAction(e -> {
            try {
                Dialog<Void> dialog = DialogUtils.openDialog("/fxml/config.fxml", controller.getStage());
                dialog.setTitle("配置");
                dialog.showAndWait();
            } catch (Exception ex) {
                alert(ex.getMessage(), Alert.AlertType.ERROR);
            }
        });

        txtUrl.setOnDragOver(event -> {

            List<File> files = event.getDragboard().getFiles();
            if (files == null || files.size() != 1) {
                return;
            }

            File file = files.get(0);
            if (file.isDirectory()
                    || !StringUtils.equalsAnyIgnoreCase(FilenameUtils.getExtension(file.getAbsolutePath()), "m3u8")) {
                return;
            }

            event.acceptTransferModes(TransferMode.LINK);

        });

        txtUrl.setOnDragDropped(event -> {
            Dragboard db = event.getDragboard();

            if (!db.hasFiles()) {
                return;
            }
            List<File> files = Collections.unmodifiableList(db.getFiles());

            txtUrl.setText(M3U8Parser.FILE_SCHEME + files.get(0).getAbsolutePath());

        });


        controller.getIsGetting().addListener((observable, oldValue, newValue) -> {
            root.setDisable(newValue);
            btnAnalysis.setText(newValue ? "解析中" : "解析");

            if (newValue) {
                txtKey.clear();
                lblKeyMethod.setText(StringUtils.EMPTY);
                controller.getTable().getItems().clear();
            }

        });

        controller.getIsDownloading().addListener((observable, oldValue, newValue) -> {
            btnDownload.setText(newValue ? "下载中" : "下载");
            disableComponents(root, newValue);
//            if(newValue){
                btnPause.setDisable(!newValue);
//            }
        });


        controller.getTable().getItems().addListener((ListChangeListener<M3U8Item>) c -> {
            if (!controller.getIsDownloading().get()) {
                btnDownload.setDisable(controller.getTable().getItems().isEmpty());
            }
        });

        btnPause.setOnAction(e -> {
            if (pauseAction != null) {
                pauseAction.run();
            }
        });
    }

    @Override
    public Window getStage() {
        return controller.getStage();
    }
}
